package com.example.gateway.config.CircuitBreaker;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
//用继承AbstractGatewayFilterFactory来创建gateway的filter的
public class MyCircuitBreakerFilter extends AbstractGatewayFilterFactory<MyCircuitBreakerFilter.Config> {

    public MyCircuitBreakerFilter() {
        super(Config.class);
    }

    @Override
//    继承来的apply方法，定义其中行为
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 在这里调用其他服务，并应用断路器
            return chain.filter(exchange).transformDeferred((Mono<Void> filtered) ->
                    applyCircuitBreaker(exchange, filtered));
        };
    }

    private Mono<Void> applyCircuitBreaker(ServerWebExchange exchange, Mono<Void> filtered) {
        return filtered.doOnError(throwable -> {
            // 在发生错误时应用断路器
            // 这里你可以添加断路器的注解或者手动包装调用其他服务的方法
            System.out.println("断路了啊哥");
        }).doOnRequest(t -> {
            // 获取调用方信息
            String callerInfo = getCallerInfo(exchange);
            System.out.println("REQUEST啦！！！");
        });
    }

    private String getCallerInfo(ServerWebExchange exchange) {
        // 获取请求头中的某些信息，比如User-Agent
        String userAgent = exchange.getRequest().getHeaders().getFirst("User-Agent");
        // 获取请求的IP地址
        String ipAddress = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        // 可以获取其他相关的信息，比如请求路径、参数等
        String requestPath = exchange.getRequest().getURI().getPath();
        String queryParams = exchange.getRequest().getQueryParams().toString();

        // 返回拼接的调用方信息
        return "IP: " + ipAddress + ", User-Agent: " + userAgent + ", Path: " + requestPath + ", Params: " + queryParams;
    }

    public static class Config {
        // 可以在这里添加配置参数
    }
}
